package org.bycloud.common.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import lombok.extern.slf4j.Slf4j;

/**
 * 实现热加载配置文件
 * 
 * @author zeroleavebaoyang
 *
 */
@Slf4j
public class PropertiesUtils {

	private static Map<String, PropertiesUtils> configMap = new HashMap<String, PropertiesUtils>();
	// 打开文件时间，判断超时使用
	private Date loadTime = null;
	private static  Locale locale = new Locale("zh","CN");
	// 资源文件
	private ResourceBundle resourceBundle = null;
	// 默认资源文件名称
	private static final String NAME = "resources";
	// 缓存时间
	private static final Integer TIME_OUT = 60 * 1000;

	// 加载 xxx.resources
	private PropertiesUtils(String name) {
		this.loadTime = new Date();
		this.resourceBundle = ResourceBundle.getBundle(name, locale);
	}

	public static synchronized PropertiesUtils me() {
		return readFile(NAME);
	}

	/**
	 * 加载配置文件xxx.properies, 间隔一段时间加载一次
	 * 
	 * name : "jdbc", "resource"
	 * 
	 * @return
	 */
	public static synchronized PropertiesUtils readFile(String name) {
		PropertiesUtils nameConfig = configMap.get(name); // 如:jdbc.properties
		if (nameConfig == null) {
			nameConfig = new PropertiesUtils(name);
			configMap.put(name, nameConfig);
		}
		if ((System.currentTimeMillis() - nameConfig.getLoadTime().getTime()) > TIME_OUT) {
			nameConfig = new PropertiesUtils(name);
			configMap.put(name, nameConfig);
		}
		return nameConfig;
	}

	public String getString(String key) {
		try {
			return resourceBundle.getString(key);
		} catch (MissingResourceException e) {
			log.error("properties error : " + e.getMessage());
			return "";
		}
	}

	public Integer getInteger(String key) {
		try {
			return Integer.parseInt(resourceBundle.getString(key));
		} catch (MissingResourceException e) {
			log.error("properties error : " + e.getMessage());
			return 0;
		}
	}

	public boolean getBoolean(String key) {
		try {
			return "true".equals(resourceBundle.getString(key));
		} catch (MissingResourceException e) {
			log.error("properties error : " + e.getMessage());
			return false;
		}
	}

	public Date getLoadTime() {
		return loadTime;
	}
}
